#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
高德地图相关路由
"""

from flask import Blueprint, jsonify, request
from core import extensions
from config.amap_config import AmapConfig

# 创建蓝图
amap_bp = Blueprint('amap', __name__, url_prefix='/amap')


@amap_bp.route('/status', methods=['GET'])
def get_amap_status():
    """获取高德地图服务状态"""
    try:
        if extensions.amap_service is None:
            return jsonify({
                "code": -1,
                "message": "高德地图服务未启用",
                "data": {
                    "enabled": False,
                    "configured": AmapConfig.validate()
                }
            })
        
        status = extensions.amap_service.get_status()
        status['service_type'] = extensions.amap_service_type
        return jsonify({
            "code": 0,
            "message": "success",
            "data": status
        })
    except Exception as e:
        return jsonify({
            "code": -1,
            "message": f"获取状态失败: {str(e)}",
            "data": None
        })


@amap_bp.route('/tools', methods=['GET'])
def list_amap_tools():
    """获取高德地图可用工具列表"""
    try:
        if extensions.amap_service is None:
            return jsonify({
                "code": -1,
                "message": "高德地图服务未启用",
                "data": None
            })
        
        tools = extensions.amap_service.list_tools()
        return jsonify({
            "code": 0,
            "message": "success",
            "data": {"tools": tools, "count": len(tools)}
        })
    except Exception as e:
        return jsonify({
            "code": -1,
            "message": f"获取工具列表失败: {str(e)}",
            "data": None
        })


@amap_bp.route('/search', methods=['POST'])
def amap_search_poi():
    """
    搜索地点（POI）
    请求体: {"keywords": "关键词", "city": "城市名（可选）"}
    """
    try:
        if extensions.amap_service is None:
            return jsonify({
                "code": -1,
                "message": "高德地图服务未启用",
                "data": None
            })
        
        data = request.get_json()
        keywords = data.get('keywords')
        city = data.get('city')
        
        if not keywords:
            return jsonify({
                "code": -1,
                "message": "缺少必要参数: keywords",
                "data": None
            })
        
        result = extensions.amap_service.search_poi(keywords, city)
        
        return jsonify({
            "code": 0 if result.get('success') else -1,
            "message": "success" if result.get('success') else result.get('error', '搜索失败'),
            "data": result.get('data')
        })
    except Exception as e:
        return jsonify({
            "code": -1,
            "message": f"搜索失败: {str(e)}",
            "data": None
        })


@amap_bp.route('/weather', methods=['POST'])
def amap_get_weather():
    """
    查询天气
    请求体: {"city": "城市名"}
    """
    try:
        if extensions.amap_service is None:
            return jsonify({
                "code": -1,
                "message": "高德地图服务未启用",
                "data": None
            })
        
        data = request.get_json()
        city = data.get('city')
        
        if not city:
            return jsonify({
                "code": -1,
                "message": "缺少必要参数: city",
                "data": None
            })
        
        result = extensions.amap_service.get_weather(city)
        
        return jsonify({
            "code": 0 if result.get('success') else -1,
            "message": "success" if result.get('success') else result.get('error', '查询失败'),
            "data": result.get('data')
        })
    except Exception as e:
        return jsonify({
            "code": -1,
            "message": f"查询天气失败: {str(e)}",
            "data": None
        })


@amap_bp.route('/route', methods=['POST'])
def amap_plan_route():
    """
    规划路线
    请求体: {"origin": "起点", "destination": "终点", "mode": "出行方式", "city": "城市（可选）"}
    mode可选: driving(驾车), walking(步行), transit(公交), riding(骑行)
    """
    try:
        if extensions.amap_service is None:
            return jsonify({
                "code": -1,
                "message": "高德地图服务未启用",
                "data": None
            })
        
        data = request.get_json()
        origin = data.get('origin')
        destination = data.get('destination')
        mode = data.get('mode', 'driving')
        city = data.get('city')
        
        if not origin or not destination:
            return jsonify({
                "code": -1,
                "message": "缺少必要参数: origin, destination",
                "data": None
            })
        
        result = extensions.amap_service.plan_route(origin, destination, mode, city)
        
        return jsonify({
            "code": 0 if result.get('success') else -1,
            "message": "success" if result.get('success') else result.get('error', '规划失败'),
            "data": result.get('data')
        })
    except Exception as e:
        return jsonify({
            "code": -1,
            "message": f"路线规划失败: {str(e)}",
            "data": None
        })


@amap_bp.route('/geocode', methods=['POST'])
def amap_geocode():
    """
    地理编码（地址转坐标）
    请求体: {"address": "地址", "city": "城市（可选）"}
    """
    try:
        if extensions.amap_service is None:
            return jsonify({
                "code": -1,
                "message": "高德地图服务未启用",
                "data": None
            })
        
        data = request.get_json()
        address = data.get('address')
        city = data.get('city')
        
        if not address:
            return jsonify({
                "code": -1,
                "message": "缺少必要参数: address",
                "data": None
            })
        
        result = extensions.amap_service.geocode(address, city)
        
        return jsonify({
            "code": 0 if result.get('success') else -1,
            "message": "success" if result.get('success') else result.get('error', '编码失败'),
            "data": result.get('data')
        })
    except Exception as e:
        return jsonify({
            "code": -1,
            "message": f"地理编码失败: {str(e)}",
            "data": None
        })


@amap_bp.route('/regeo', methods=['POST'])
def amap_reverse_geocode():
    """
    逆地理编码（坐标转地址）
    请求体: {"location": "经度,纬度"}
    """
    try:
        if extensions.amap_service is None:
            return jsonify({
                "code": -1,
                "message": "高德地图服务未启用",
                "data": None
            })
        
        data = request.get_json()
        location = data.get('location')
        
        if not location:
            return jsonify({
                "code": -1,
                "message": "缺少必要参数: location",
                "data": None
            })
        
        result = extensions.amap_service.reverse_geocode(location)
        
        return jsonify({
            "code": 0 if result.get('success') else -1,
            "message": "success" if result.get('success') else result.get('error', '编码失败'),
            "data": result.get('data')
        })
    except Exception as e:
        return jsonify({
            "code": -1,
            "message": f"逆地理编码失败: {str(e)}",
            "data": None
        })


@amap_bp.route('/call_tool', methods=['POST'])
def amap_call_tool():
    """
    直接调用MCP工具
    请求体: {"tool_name": "工具名", "arguments": {...}}
    """
    try:
        if extensions.amap_service is None:
            return jsonify({
                "code": -1,
                "message": "高德地图服务未启用",
                "data": None
            })
        
        data = request.get_json()
        tool_name = data.get('tool_name')
        arguments = data.get('arguments', {})
        
        if not tool_name:
            return jsonify({
                "code": -1,
                "message": "缺少必要参数: tool_name",
                "data": None
            })
        
        result = extensions.amap_service.call_tool(tool_name, arguments)
        
        return jsonify({
            "code": 0 if result.get('success') else -1,
            "message": "success" if result.get('success') else result.get('error', '调用失败'),
            "data": result.get('data')
        })
    except Exception as e:
        return jsonify({
            "code": -1,
            "message": f"工具调用失败: {str(e)}",
            "data": None
        })

